﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SenGe.Application;
using SenGe.Domain;
using SenGe.Domain.Utils;

namespace SenGe.Web.Controllers
{
    /// <summary>
    /// 用户管理相关控制器
    /// </summary>
    [Authorize]
    public class UserController : BaseController
    {
        private readonly ISenUserService _userService;
        private readonly ILogger<HomeController> _logger;

        public UserController(ILogger<HomeController> logger, ISenUserService senUserService)
        {
            _logger = logger;
            _userService = senUserService;
        }

        /// <summary>
        /// 用户列表
        /// </summary>
        /// <returns></returns>
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 查看用户详情
        /// </summary>
        /// <param name="id">用户编号</param>
        /// <returns></returns>
        public IActionResult Detail(long id)
        {
            ViewData["MenuIndex"] = "/user/index";
            return View();
        }

        /// <summary>
        /// 新增或编辑用户信息
        /// </summary>
        /// <param name="id">用户编号</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> AddOrUpdate(long id = 0)
        {
            UserRegisterModel? dbItem = null;
            if (id > 0)
            {
                dbItem = await _userService.GetUserRegisterModel(id);
            }
            ViewData["MenuIndex"] = "/user/index";
            return View(dbItem);
        }

        /// <summary>
        /// 新增或编辑用户信息
        /// </summary>
        /// <param name="model">用户模型</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AddOrUpdate([FromForm] UserRegisterModel model)
        {
            //验证输入
            model.ResultMessage = string.Empty;
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            UserRegisterCheckResult checkResult = await _userService.CheckRegisterInfo(model);
            if (checkResult == UserRegisterCheckResult.NameExists)
            {
                model.ResultMessage = "该用户昵称已存在！";
                return View(model);
            }
            else if (checkResult == UserRegisterCheckResult.UserNameExists)
            {
                model.ResultMessage = "该用户名已存在！";
                return View(model);
            }
            else if (checkResult == UserRegisterCheckResult.PhoneExists)
            {
                model.ResultMessage = "该手机号码已存在！";
                return View(model);
            }
            DtoCurrentUser? currentUser = GetCurrentUserInfo();
            if (currentUser == null)
            {
                model.ResultMessage = "当前登录用户信息有误，请退出后重新登入！";
                return View(model);
            }
            model.UpdatedUserId = currentUser.Id;
            model.UpdatedUserName = currentUser.Name;

            ViewData["MenuIndex"] = "/user/index";
            return View();
        }

        /// <summary>
        /// 新增用户信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Add()
        {
            ViewData["MenuIndex"] = "/user/index";
            return View();
        }

        /// <summary>
        /// 新增用户信息
        /// </summary>
        /// <param name="model">用户模型</param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Add([FromForm] UserRegisterModel model)
        {
            //验证输入
            model.ResultMessage = string.Empty;
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            ViewData["MenuIndex"] = "/user/index";
            return View();
        }

        /// <summary>
        /// 编辑用户信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Edit()
        {
            ViewData["MenuIndex"] = "/user/index";
            return View();
        }

        /// <summary>
        /// 编辑用户信息
        /// </summary>
        /// <param name="model">用户模型</param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Edit([FromForm] SenUser model)
        {
            ViewData["MenuIndex"] = "/user/index";
            return View();
        }

        public IActionResult TestIndex()
        {
            return View();
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="model">修改模型</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> ChangePWD(ChangePwdModel model)
        {
            ApiResult result = new ApiResult()
            {
                Success = false,
                Message = "修改密码失败！"
            };
            if (model == null ||
                string.IsNullOrEmpty(model.OldPassword) ||
                string.IsNullOrEmpty(model.NewPassword) ||
                string.IsNullOrEmpty(model.ConfirmPassword))
            {
                result.Message = "修改信息不能为空！";
                return result;
            }
            else if (model.NewPassword != model.ConfirmPassword)
            {
                result.Message = "新密码两次输入不一致！";
                return result;
            }
            DtoCurrentUser? currentUser = GetCurrentUserInfo();
            if (currentUser == null)
            {
                result.Message = "当前用户信息有误！";
                return result;
            }
            DtoSenUser? dbItem = await _userService.GetUserById(currentUser.Id);
            if (dbItem == null)
            {
                result.Message = "当前用户信息有误！";
                return result;
            }
            else if (!SecurePasswordHasher.VerifyPassword(dbItem.PassWord, model.OldPassword))
            {
                result.Message = "原密码不正确！";
                return result;
            }
            dbItem.PassWord = SecurePasswordHasher.HashPassword(model.NewPassword);
            if (await _userService.ChangePassWord(dbItem))
            {
                result.Success = true;
                result.Message = "修改密码成功！";
            }
            return result;
        }
    }
}
